<template>
  <ul class="tab">
    <li
      v-for="tab in serializedTabs"
      :key="tab.value"
      class="tab-item hover-active disabled-select mr-4 cursor-pointer"
      :class="{ active: value === tab.value }"
      @click.stop.prevent="updateTab(tab)"
    >
      <slot v-bind="{ tab }">
        <slot v-bind="{ tab }" name="prepend" />
        {{ $t(tab.label) }}
        <slot v-bind="{ tab }" name="append" />
      </slot>
    </li>
  </ul>
</template>

<script>
function isStringTab(lst) {
  return lst.every(t => typeof t === 'string');
}

function isObjectTab(lst) {
  return lst.every(t => t && typeof t === 'object' && t.label);
}

function tabsValidator(lst) {
  return Array.isArray(lst) && (isStringTab(lst) || isObjectTab(lst));
}

export default {
  props: {
    tabs: {
      type: Array,
      required: true,
      validator: tabsValidator
    },
    value: {
      type: [String, Number],
      required: true
    }
  },

  computed: {
    serializedTabs() {
      if (!Array.isArray(this.tabs)) return [];
      if (isStringTab(this.tabs)) {
        return this.tabs.map((label, value) => ({ label, value }));
      }
      if (isObjectTab(this.tabs)) {
        return this.tabs.map((t, value) => ({ value, ...t }));
      }
      return this.tabs;
    }
  },

  methods: {
    updateTab(tab) {
      if (tab.value === this.value) return;
      this.$emit('input', tab.value, tab);
      this.$emit('select', tab.value, tab);
    }
  }
};
</script>

<style lang="scss" scoped>
.tab {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  height: 32px;
  align-items: center;

  .tab-item {
    height: 32px;
    background: rgba(12, 12, 28, 0.04);
    border-radius: 8px;
    font-size: 14px;
    color: rgba(12, 12, 28, 0.7);
    padding: 0 12px;
    line-height: 32px;
  }

  .active {
    background: #fa4646;
    border-radius: 8px;
    color: #ffffff;
  }
}
</style>

